package edu.whu.xterm.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import edu.whu.xterm.Article;
import edu.whu.xterm.BoardArticle;
import edu.whu.xterm.R;
import edu.whu.xterm.http.RequestBuilder;
import edu.whu.xterm.util.Constants;

public class BoardArticleListActivity extends GDLoadingActivity implements AdapterView.OnItemClickListener {

	public static final String KEY_BOARD_NAME = "board_name";

	public static final String KEY_BOARD_DESC = "board_desc";

	private static final int HTTP_REQUEST_LOADER = 1;

	ListView articlesView;

	View moreView;

	private String boardName;

	private List<String> bms;

	LoaderManager loaderManeger;

	BaseAdapter adapter;

	List<Article> data;

	List<Map<String, String>> mData;

	private static final String[] FROM = { "title", "author", "board" };
	private static final int[] TO = { R.id.topic_title, R.id.topic_author, R.id.topic_board };

	public BoardArticleListActivity() {
		super();
		mData = new ArrayList<Map<String, String>>();
		data = new ArrayList<Article>();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.activity_loading_list_view);
		articlesView = (ListView) findViewById(android.R.id.list);
		moreView = getLayoutInflater().inflate(R.layout.replies_more, null);
		articlesView.addFooterView(moreView);
		articlesView.setFastScrollEnabled(true);
		initLoadingView(articlesView);
		articlesView.setOnItemClickListener(this);
		boardName = getIntent().getStringExtra(KEY_BOARD_NAME);
		getGActionBar().setTitle(getIntent().getStringExtra(KEY_BOARD_DESC));

		moreView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				moreView.findViewById(R.id.loading_widget).setVisibility(View.VISIBLE);
				loaderManeger.getLoader(HTTP_REQUEST_LOADER).forceLoad();
			}
		});

		adapter = new SimpleAdapter(getApplicationContext(), mData, R.layout.topic_list_item, FROM, TO);
		articlesView.setAdapter(adapter);
		initLoader();
		executeLoadTask();
	}

	private void initLoader() {
		loaderManeger = getSupportLoaderManager();
		loaderManeger.initLoader(HTTP_REQUEST_LOADER, null,
				new LoaderManager.LoaderCallbacks<List<? extends Article>>() {

					@Override
					public Loader<List<? extends Article>> onCreateLoader(int arg0, Bundle arg1) {
						Loader<List<? extends Article>> loader = new AsyncTaskLoader<List<? extends Article>>(
								getApplicationContext()) {
							private int page = 1;

							@Override
							public List<? extends Article> loadInBackground() {
								String url = Constants.SITE + Constants.PATH_BOARD + "?name=" + boardName
										+ ((page > 1) ? ("&page=" + page) : "");
								try {
									Document document = RequestBuilder.getBuilder().pageRequest(url).call();
									if (page == 1) {
										Elements bmElements = document.select("a[href^=dispuser]");
										bms = new ArrayList<String>(bmElements.size());
										for (Element ele : bmElements) {
											bms.add(ele.text());
										}
									}
									Elements jsElements = document.select("script[language=JavaScript]");
									Element articleElement = null;
									for (Element ele : jsElements) {
										if (ele.data().indexOf("boardName") > 0)
											articleElement = ele;
									}
									if (articleElement == null) {
										return null;
									}
									String articleText = articleElement.data();
									List<Post> posts = parse2Posts(articleText);
									List<BoardArticle> articles = parse2BoardArticles(posts);
									data.addAll(articles);
									return articles;
								} catch (Exception e) {
									e.printStackTrace();
									return null;
								}
							}

							@Override
							public void deliverResult(List<? extends Article> data) {
								if (data != null) {
									page++;
									adapter.notifyDataSetChanged();
									loadSuccessed();
								} else {
									loadFailed();
								}
								moreView.findViewById(R.id.loading_widget).setVisibility(View.GONE);
							}

						};
						return loader;
					}

					@Override
					public void onLoadFinished(Loader<List<? extends Article>> arg0, List<? extends Article> arg1) {
					}

					@Override
					public void onLoaderReset(Loader<List<? extends Article>> arg0) {
					}
				});
	}

	List<Post> parse2Posts(String text) {
		int len = text.length();
		int p = 0;
		List<Post> posts = new ArrayList<Post>();
		while (p < len) {
			int originStart = text.indexOf("ost(", p) + 4;
			if (originStart <= 3) {
				break;
			}
			Post post = new Post();
			int originEnd = text.indexOf(");", originStart);
			String origin = text.substring(originStart, originEnd);
			post.origin = origin;
			int lastReplyStart = text.indexOf("ost(", originEnd) + 4;
			int lastReplyEnd = text.indexOf(");", lastReplyStart);
			String lastReply = text.substring(lastReplyStart, lastReplyEnd);
			post.lastReply = lastReply;

			int writePostStart = text.indexOf("ost(", lastReplyEnd) + 4;
			int writePostEnd = text.indexOf(");", writePostStart);
			String writePost = text.substring(writePostStart, writePostEnd);
			post.writePost = writePost;

			p = writePostEnd;
			posts.add(post);

		}
		return posts;
	}

	List<BoardArticle> parse2BoardArticles(List<Post> posts) {
		List<BoardArticle> articles = new ArrayList<BoardArticle>(posts.size());
		for (Post post : posts) {
			try {
				BoardArticle article = new BoardArticle();
				StringTokenizer st = new StringTokenizer(post.origin, "','");
				article.id = Integer.valueOf(st.nextToken());
				st.nextToken();
				article.author = st.nextToken();
				st.nextToken();
				article.time = st.nextToken();
				st.nextToken();
				article.flag = st.nextToken();

				st = new StringTokenizer(post.lastReply, "','");
				article.lastReplyId = Integer.valueOf(st.nextToken().trim());
				st.nextToken();
				article.lastReplyAuthor = st.nextToken();
				st.nextToken();
				article.lastReplyTime = st.nextToken();
				st.nextToken();
				article.lastReplyFlag = st.nextToken();

				st = new StringTokenizer(post.writePost, "','");
				article.position = Integer.valueOf(st.nextToken().trim());
				st.nextToken();
				article.title = st.nextToken();
				article.postCount = Integer.valueOf(st.nextToken().trim());
				st.nextToken();
				st.nextToken();
				article.originExist = st.nextToken().trim().equals("1");
				article.hasAttatch = st.nextToken().trim().equals("1");
				article.board = boardName;
				articles.add(article);
				Map<String, String> data = new HashMap<String, String>();
				data.put(FROM[0], article.title);
				data.put(FROM[1], article.author);
				data.put(FROM[2], article.board);
				mData.add(data);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return articles;
	}

	@Override
	public void executeLoadTask() {
		loaderManeger.getLoader(HTTP_REQUEST_LOADER).forceLoad();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		String url = Constants.SITE + Constants.PATH_DISPLAY_ARTICLE_WFORUM + "?boardName=" + boardName + "&ID="
				+ data.get(position).id;
		Intent intent = new Intent(getApplicationContext(), TopicAndReplyWforumActivity.class);
		intent.putExtra(TopicAndReplyWforumActivity.KEY_URL, url);
		startActivity(intent);
	}

	private static class Post {
		String origin;
		String lastReply;
		String writePost;
	}

}
